package com.app.auth.config;

import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import javax.annotation.PostConstruct;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;

@Component
public class ApiScanComponet {
    @Autowired
    private RequestMappingHandlerMapping requestMapping;

    @PostConstruct
    public void init() {

        Map<RequestMappingInfo, HandlerMethod> handlerMethods = requestMapping.getHandlerMethods();


        for (Map.Entry<RequestMappingInfo, HandlerMethod> entry :
                handlerMethods.entrySet()) {
            try {
                info(entry.getKey(), entry.getValue());
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            } catch (InstantiationException e) {
                e.printStackTrace();
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            }
        }


    }

    private void info(RequestMappingInfo mappingInfo, HandlerMethod method) throws IllegalAccessException, InvocationTargetException, InstantiationException, NoSuchMethodException {
        System.out.println("api 协议: " + mappingInfo.getMethodsCondition().toString());
        System.out.println("api 路由: " + mappingInfo.getPatternsCondition().toString());
        ApiOperation apiOperation = method.getMethodAnnotation(ApiOperation.class);
        if (apiOperation != null) {
            System.out.println("api 描述: " + apiOperation.value());
        }
        System.out.println(method.getMethod().getReturnType().getTypeName());
        System.out.println(method.getMethod().getGenericReturnType().getTypeName());
        MethodParameter res = method.getReturnType();
        if (res != null) {
            Constructor<?> constructor = res.getConstructor();
            if (constructor != null)
                System.out.println("api 返回值: " + constructor.newInstance().toString());
        }
        System.out.println("------------------");
    }

}
